// 使用 contextBridge 来安全地暴露 API 给渲染进程
const { contextBridge,ipcRenderer } = require('electron')
const api = {
  send: (channel, data) => {
    ipcRenderer.send(channel, data)
  },
  receive: (channel, func) => {
    ipcRenderer.on(channel, (event, ...args) => func(...args))
  },
  getUserId: () => ipcRenderer.invoke('get-user-id'), // 新增方法
  proxyFetch: (url, options) => ipcRenderer.invoke('proxy-fetch', url, options),
  getUrls: () => ipcRenderer.invoke('get-urls'),
  getCourseId: () => ipcRenderer.invoke('get-course-id'),
  getToken: () => ipcRenderer.invoke('get-token'),
}

// 将 API 暴露给渲染进程
contextBridge.exposeInMainWorld('electronAPI', api)
ipcRenderer.on('main-eval', (event, code) => {
  
})
contextBridge.exposeInMainWorld('webAPI', {
    // 为特殊窗口定制的 API
    getUserId: () => ipcRenderer.invoke('get-user-id'),
    getUrls: () => ipcRenderer.invoke('get-urls'),
    getCourseId: () => ipcRenderer.invoke('get-course-id'),
    getToken: () => ipcRenderer.invoke('get-token'),
    navigate: (url) => ipcRenderer.send('navigate', url),

});

contextBridge.exposeInMainWorld('loadJavaScript', loadJavaScript)
contextBridge.exposeInMainWorld('loadJavaScript', loadJavaScript)
async function loadJavaScript(url,time){
  return new Promise(next => {
    let script = document.createElement('script')
    if(/\.js$/.test(url)){
      script.src = url
    }else{
      script.innerHTML = url
    }
    document.body.appendChild(script)
    setTimeout(next,time || 500)
  })
}
setTimeout(()=>{
  var a = {}
  {{tools}}
  function ajax(meth,url,data,args){
    return new Promise(resolve => {
      args = args || {};
      args.meth = meth || 'GET';
      args.data = data;
      args.headers = args.headers || {}
      let ajaxHeaders = a.Storage.get('ajaxHeader') || {}
      args.headers = Object.assign(args.headers,ajaxHeaders)
      args.loading = args.loading || (args.meth == 'GET' ? false : undefined)
      if(args.loading === true) args.loading = undefined
      url = url.replace(new RegExp('^{(.+)}', 'g'), function($0, $1) {
        return a.Storage.get($1) || ('{' + $1 + '}');
      })
      if (url.indexOf('http') != 0) url = a.Storage.get('APIURL') + url
      var ajax = new a.Ajax(url, function(ret) {
        if (args.errNotify !== false && ret.errorMsg && a.showToast) a.showToast(ret.errorMsg);
        resolve(ret);
      }, args)
      ajax.action()
    })
  }
  a.get = async function(url,data,args){
    return await ajax('GET',url,data,args);
  }

  a.post = async function(url,data,args){
    return await ajax('POST',url,data,args);
  }

  a.put = async function(url,data,args){
    return await ajax('PUT',url,data,args);
  }

  a.delete = async function(url,data,args){
    return await ajax('DELETE',url,data,args);
  }
  contextBridge.exposeInMainWorld('Y', a)
  let thirdWebPreload
},200)

